﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Media.Animation;
using System.Threading;
using System.Diagnostics;
using System.ComponentModel;
using System.Windows.Threading;
using System.Net;
using System.IO;

namespace JustPlus
{
    /// <summary>
    /// LoginPanel.xaml 的交互逻辑
    /// </summary>
    public partial class LoginPanel : UserControl
    {
        private string CaptchaUrl;
        private string CaptchaID;
        public static bool HasLoginOn = false;//
        public static string LoginName;
        public static int LoginPlayed;
        public static int LoginLiked;
        public static int LoginBanned;

        public LoginPanel()
        {
            InitializeComponent();
            //this.DataContext = new VM(this.Dispatcher);
            textBox1.Text = Properties.Settings.Default.UserID;
            passwordBox1.Password = Properties.Settings.Default.UserPassword;
            this.Loaded += new RoutedEventHandler(UpdateCaptcha);
        }

        // 更新验证码
        public void UpdateCaptcha(object sender, RoutedEventArgs e)
        {
            CaptchaUrl = null;
            ThreadPool.QueueUserWorkItem(new WaitCallback((state) =>
            {
                CaptchaID = new ConnectionBase().Get("http://douban.fm/j/new_captcha");
                CaptchaID = CaptchaID.Trim('\"');
                CaptchaUrl = @"http://douban.fm/misc/captcha?size=m&id=" + CaptchaID;

                Dispatcher.BeginInvoke(new Action(() =>
                {
                    if (string.IsNullOrEmpty(CaptchaID))
                    {
                        CaptchaID = null;
                        CaptchaUrl = null;
                    }
                    else
                    {
                        BitmapImage captcha = new BitmapImage(new Uri(CaptchaUrl, UriKind.Absolute));
                        image1.Source = captcha;
                        captcha.DownloadCompleted += delegate
                        {
                            label4.Content = "";
                        };
                    }
                }));
            }));
        }

        //登录
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            //
            Parameters parameters = new Parameters();
            parameters.Add("source", "radio");
            parameters.Add("alias", textBox1.Text.Trim());
            parameters.Add("form_password", passwordBox1.Password.Trim());
            parameters.Add("captcha_solution", textBox2.Text.Trim());
            parameters.Add("captcha_id", CaptchaID);
            if (defCheckBox1.isChecked)
                parameters.Add("remember", "on");
            ThreadPool.QueueUserWorkItem(new WaitCallback((state) =>
            {
                string LogOnJson = new ConnectionBase().Post("http://douban.fm/j/login", Encoding.UTF8.GetBytes(parameters.ToString()));
                LogOnResult logonresult = LogOnResult.FromJson(LogOnJson);
                Dispatcher.Invoke(new Action(() =>
                {
                    if (logonresult == null)
                    {
                        label7.Content = @"登录失败，请检查网络或者重新登录！";
                        HasLoginOn = false;
                        return;
                    }
                    if (logonresult.r == 1)
                    {
                        label7.Content = logonresult.err_msg;
                        HasLoginOn = false;
                    }
                    else if (logonresult.r == 0)
                    {
                        if (defCheckBox2.isChecked)
                        {
                            Properties.Settings.Default.UserID = textBox1.Text;
                            Properties.Settings.Default.UserPassword = passwordBox1.Password;
                            Properties.Settings.Default.Save();
                        }
                        else
                        {
                            Properties.Settings.Default.UserID = "";
                            Properties.Settings.Default.UserPassword = "";
                            Properties.Settings.Default.Save();
                        }
                        HasLoginOn = true;
                        LoginName = logonresult.user_info.name;
                        LoginPlayed = logonresult.user_info.play_record.played;
                        LoginLiked = logonresult.user_info.play_record.liked;
                        LoginBanned = logonresult.user_info.play_record.banned;

                        MainWindow mwnd = (MainWindow)Application.Current.MainWindow;
                        mwnd.stackPanel1.Children.Clear();
                        LogoutPanel logoutpanel = new LogoutPanel();
                        mwnd.stackPanel1.Children.Add(logoutpanel);
                        logoutpanel.label1.Content = logonresult.user_info.name;
                        logoutpanel.label2.Content = "累计收听" + logonresult.user_info.play_record.played.ToString() + "首";
                        logoutpanel.label3.Content = "加红心" + logonresult.user_info.play_record.liked.ToString() + "首";
                        logoutpanel.label4.Content = "不再收听" + logonresult.user_info.play_record.banned.ToString() + "首";
                    }

                }));
            }));
        }

        //刷新验证码
        private void label4_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            UpdateCaptcha(null, null);
        }

        //转入注册账号页面
        private void button3_Click(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Process.Start("http://www.douban.com/accounts/register");
        }

        //离开当前界面，进入默认主界面
        private void Grid_MouseLeave(object sender, MouseEventArgs e)
        {
            if (!HasLoginOn)
            {
                MainWindow mwnd = (MainWindow)Application.Current.MainWindow;
                mwnd.stackPanel1.Children.Clear();
                mwnd.stackPanel1.Children.Add(mwnd.stackPanel2);
                mwnd.stackPanel1.Children.Add(mwnd.stackPanel3);
            }
        }
    }
}
